<template>
  <div class="enterprise-management">
    <!-- 第一行：搜索框和查询按钮 -->
    <div class="search-bar">
      <el-form :inline="true" label-width="120px">
        <el-form-item label="企业名称：">
          <el-input
            placeholder="请输入企业名称"
            clearable
            v-model="params.name"
            @clear="search"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <!-- 第二行：新增企业按钮 -->
    <div class="toolbar">
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="$router.push('/park/enterprise/addEnterprise')"
      >
        新增企业
      </el-button>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <el-table
        @expand-change="expandChange"
        :data="enterpriseList"
        style="width: 100%"
        stripe
        empty-text="暂无数据"
        :header-cell-style="{
          background: '#f5f7fa',
          color: '#333',
          fontWeight: 'bold',
        }"
      >
        <el-table-column type="expand">
          <template v-slot:default="props">
            <el-table :data="props.row.rentList" style="width: 100%">
              <el-table-column
                label="租赁楼宇"
                prop="buildingName"
              ></el-table-column>
              <el-table-column label="起始时间" prop="startTime">
                <template #default="rentObj">
                  {{ rentObj.row.startTime }}至{{ rentObj.row.endTime }}
                </template>
              </el-table-column>
              <el-table-column label="合同状态" prop="status">
                <template #default="rentObj">
                  <el-tag :type="formateInfoType(rentObj.row.status)">
                    {{ formateStatus(rentObj.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" fixed="right">
                <template #default="scope">
                  <!-- 在这里可以放置操作按钮，比如编辑或删除 -->
                  <div style="display: flex">
                    <el-button size="mini" @click="rentOut(scope.row.id)" :disabled='scope.row.status===3'>
                      退租
                    </el-button>
                    <el-button
                      size="mini"
                      type="danger"
                      @click="handleDelete(scope.$index, scope.row)"
                       :disabled='scope.row.status !==3'
                    >
                      删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <!-- 序号 -->
        <el-table-column type="index" label="序号" :index="indexMethod" />
        <!-- 企业名称 -->
        <el-table-column prop="name" label="企业名称" />
        <!-- 联系人 -->
        <el-table-column prop="contact" label="联系人" />
        <!-- 联系电话 -->
        <el-table-column prop="contactNumber" label="联系电话" />
        <!-- 操作 -->
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="addContract(row.id)"
              >添加合同</el-button
            >
            <el-button type="text" size="small" @click="reviewTheContract(row.id)">查看</el-button>
            <el-button type="text" size="small" @click="toEditPage(row.id)"
              >编辑</el-button
            >
            <el-button type="text" size="small" @click="delPage(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <div class="pagination-container">
        <div class="total-count">共{{ total }}条</div>
        <el-pagination
          class="custom-pagination"
          layout="prev, pager, next"
          :total="total"
          :page-size="params.pageSize"
          @current-change="currentChange"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      title="租赁信息"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" label-position="top" :rules="rules" ref="ruleForm">
        <el-form-item
          label="租赁楼宇"
          :label-width="formLabelWidth"
          prop="buildingId"
        >
          <el-select v-model="form.buildingId" placeholder="请选择">
            <el-option
              v-for="item in leasePremises"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="起始日期"
          :label-width="formLabelWidth"
          prop="IntervalDates"
        >
          <el-date-picker
            v-model="form.IntervalDates"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="合同上传"
          :label-width="formLabelWidth"
          prop="contractId"
        >
          <el-upload
            ref="upload"
            class="upload-demo"
            action="#"
            :http-request="httpRequest"
            :before-upload="beforeUpload"
            :limit="2"
            :on-exceed="onExceed"
            :on-remove="handleRemove"
          >
            <el-button slot="trigger" size="small" type="primary"
              >选取文件</el-button
            >
            <div slot="tip" class="el-upload__tip">
              只能上传.doc,.docx, .pdf文件，且不超过5MB
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog('ruleForm')">取消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getEnterpriseListAPI,
  delEnterpriseDetailAPI,
  getRentBuildingAPI,
  addRentBuildingAPI,
  getEnterpriseRentAPI,
  updateEnterpriseRentAPI,
} from "@/api/enterprise";
import { uploadFileAPI } from "@/api/common";
export default {
  data() {
    return {
      enterpriseList: [],
      listLoading: true,
      params: {
        name: "",
        page: 1,
        pageSize: 10,
      },
      total: 0, //默认总页数
      dialogVisible: false,
      form: {
        buildingId: null,
        startTime: "",
        endTime: "",
        contractUrl: "",
        contractId: null,
        type: 0,
        enterpriseId: null,
        IntervalDates: [], // 区间日期
      },
      rules: {
        buildingId: [
          { required: true, message: "请输入活动名称", trigger: "change" },
        ],
        IntervalDates: [
          { required: true, message: "请选择时间范围", trigger: "change" },
        ],
        contractId: [
          {
            required: true,
            message: "请至少选择一个活动性质",
            trigger: "blur",
          },
        ],
      },
      formLabelWidth: "120px",
      leasePremises: [], // 租赁楼宇
      tableData: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 页面刷新
    async getList() {
      this.listLoading = true;
      const res = await getEnterpriseListAPI(this.params);
      // 父级表格数据
      this.enterpriseList = res.data.rows.map((item) => {
        return {
          ...item,
          rentList: [],
        };
      });
      this.total = res.data.total;
    },
    // 点击每一页
    currentChange(page) {
      this.params.page = page;
      this.getList();
    },
    // 自定义索引id
    indexMethod(index) {
      return (this.params.page - 1) * this.params.pageSize + index + 1;
    },
    // 查询,清空
    search() {
      this.params.page = 1;
      this.getList();
    },
    // 编辑
    toEditPage(id) {
      this.$router.push({
        path: "/park/enterprise/addEnterprise",
        query: {
          id: id,
        },
      });
    },
    //删除
    delPage(id) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            await delEnterpriseDetailAPI(id);
            this.getList();
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            if (this.enterpriseList.length === 1 && this.params.page === 1) {
              this.params.page--;
            }
          } catch (error) {
            console.error("Error during deletion:", error);
            this.$message({
              type: "error",
              message: "取消删除",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 添加合同-租赁楼宇列表
    async addContract(id) {
      this.dialogVisible = true;
      const res = await getRentBuildingAPI();
      this.leasePremises = res.data;
      this.form.enterpriseId = id; //项目id
    },
    // 上传文件
    async httpRequest({ file }) {
      const formData = new FormData();
      formData.append("file", file);
      formData.append("type", 2);
      const res = await uploadFileAPI(formData);
      this.form.contractUrl = res.data.url;
      this.form.contractId = res.data.id;
      this.$refs.ruleForm.validateField("contractId");
    },
    beforeUpload(file) {
      const fileType = [
        "application/x-compressed",
        "application/x-zip-compressed",
        "application/msword",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "application/pdf",
      ];
      if (!fileType.includes(file.type)) {
        this.$message.error("图片格式不正确");
        return false;
      }
      if (file.size / 1024 / 1024 > 5) {
        this.$message.error("图片大小不能超过5M");
        return false;
      }
    },
    // 文件钩子函数
    onExceed(files, fileList) {
      this.$message.error(`上传得文件只能是小于${fileList.length}`);
    },
    // 移除文件
    handleRemove(file, fileList) {
      this.form.contractUrl = "";
      this.form.contractId = "";
      this.$refs.ruleForm.validateField("contractId");
    },
    // 确定合同
    submitForm(ruleForm) {
      this.$refs[ruleForm].validate(async (valid) => {
        if (valid) {
          const [startTime, endTime] = this.form.IntervalDates;
          this.form.startTime = startTime;
          this.form.endTime = endTime;
          delete this.form.IntervalDates;
          const res = await addRentBuildingAPI(this.form);
          this.closeDialog();
          this.$message.success("合同添加成功");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 取消
    closeDialog(ruleForm) {
      // 取消数据
      this.dialogVisible = false;
      this.form = {
        buildingId: null,
        startTime: "",
        endTime: "",
        contractUrl: "",
        contractId: null,
        type: 0,
        enterpriseId: null,
        IntervalDates: [], // 区间日期
      };
      // 取消校验
      this.$refs[ruleForm].resetFields();
      // 删除上传取消后的文件
      this.$refs.upload.clearFiles();
    },
    // 展开行事件
    async expandChange(row, expandedRows) {
      // 判断当前的状态是展开还是关闭,优化
      const isInclude = expandedRows.find((item) => item.id === row.id);
      if (!isInclude) return;
      const res = await getEnterpriseRentAPI(row.id);
      row.rentList = res.data;
    },
    //状态
    formateStatus(status) {
      const Map = {
        0: "待生效",
        1: "生效中",
        2: "已到期",
        3: "已退租",
      };
      return Map[status];
    },
    // 标签状态
    formateInfoType(status) {
      const Map = {
        0: "warring",
        1: "success",
        2: "info",
        3: "danger",
      };
      return Map[status];
    },
    // 退租
    rentOut(id) {
      console.log(id, "33");
      this.$confirm("此操作将退租, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            await updateEnterpriseRentAPI(id);
            this.getList(); // 确保此方法已定义并正常工作
            this.$message({
              type: "success",
              message: "退租成功!",
            });
          } catch (error) {
            console.error("退租失败:", error);
            this.$message({
              type: "error",
              message: "退租失败，请稍后重试。",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消退租",
          });
        });
    },
    // 合同查看点击事件
    reviewTheContract(id) {
      this.$router.push({
        path: '/contractDetails',
        query: {
          id: id
        }
      })
    }
  },
};
</script>
<style scoped>
/* 整体布局样式 */
.enterprise-management {
  padding: 20px;
  background: #fff;
}

/* 工具栏：新增企业按钮 */
.toolbar {
  margin-bottom: 20px;
}

/* 搜索栏 */
.search-bar {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 0;
}

.pagination-container {
  display: flex;
  align-items: center;
  justify-content: flex-end; /* 在左右两端对齐 */
  padding: 20px;
}
.total-count {
  font-size: 14px;
}
.el-form-item {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.el-button {
  margin-left: 10px;
}

.upload-demo .el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.el-input,
.el-date-picker {
  width: 100%;
}

.el-dialog__header {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.el-dialog__title {
  font-weight: bold;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
